package com.qf.listen;

import com.qf.Constant.RabbitMqConstant;
import com.qf.entity.OrderDetailEntity;
import com.qf.entity.OrderEntity;
import com.qf.entity.StockParam;
import com.qf.feign.OrderService;
import com.qf.service.StockService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 你的名字
 * @Date: 2021/07/28/20:25
 * @Description:
 */
@Component
@Slf4j
public class RabbitMQListen {
    @Autowired
     private OrderService orderService;
  @Autowired
  private StockService stockService;
    @RabbitListener(queues = RabbitMqConstant.STOCK_DLX_QUEUE)
        public void unLockStock(OrderEntity orderEntity, Channel channel, Message message){
        String oid = orderEntity.getOid();
        OrderEntity order = orderService.getInfoByOid(oid);
        Integer status = order.getStatus();
        try {
            switch (status){
                case 1:
                    //未支付
                    log.debug("还未支付......");
                    unlockstocks(order);
                    break;
                case 2:
                    //已支付
                    log.debug("已支付....");
                    break;
                case 3:
                    //已取消
                    log.debug("已取消.....");
                    unlockstocks(order);
                    break;
                case 4:
                    //已超时
                    log.debug("已超时......");
                    //释放库存
                    unlockstocks(order);
                    break;

            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void unlockstocks(OrderEntity orderEntity) {
        List<OrderDetailEntity> orderDetailEntityList = orderEntity.getOrderDetailEntityList();
       List<StockParam> list=new ArrayList<>();
        for (OrderDetailEntity orderDetailEntity : orderDetailEntityList) {
            Integer sum = orderDetailEntity.getSum();
            Integer gid = orderDetailEntity.getGid();
            StockParam stockParam = new StockParam();
            stockParam.setGid(gid);
            stockParam.setSum(sum);
            stockParam.setWid(1);
            list.add(stockParam);
        }
      stockService.unlock(list);
    }
}
